package com.pb.infra.auth.service;

import com.pb.infra.oth.util.JwtTokenConfig;
import com.pb.infra.oth.entity.common.Result;
import com.pb.infra.auth.entity.pbsys.PriviLine;
import com.pb.infra.auth.mapper.custom.PriviLineCustomMapper;

import com.pb.infra.auth.mapper.pbsys.PriviLineMapper;
import com.pb.infra.oth.util.Constant;
import com.pb.infra.oth.util.DateTimeUtil;
import com.pb.infra.oth.util.Helper;
import com.pb.infra.oth.util.StringUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 条线管理
 *
 * @author liudebao
 * @date 2020/12/25
 */
@Service
public class PriviLineService {

    /**
     * 条线单表DAO映射
     */
    @Resource
    private PriviLineMapper priviLineMapper;

    /**
     * 条线多表DAO映射
     */
    @Resource
    private PriviLineCustomMapper priviLineCustomMapper;

    /**
     * jwttoken配置类
     */
    @Resource
    private JwtTokenConfig jwtTokenConfig;

    /**
     * 查询条线管理
     * @param map
     * @return
     */
    public Result select(Map<String, Object> map, HttpServletRequest request) {
        //一般查询时传递过来的参数有可能不全，需要补齐避免Mybatis报错（比如模糊查询的用户名称条件缺失）
        Helper.supplementParamMap(map, "lineId");
        Helper.supplementParamMap(map, "lineName");
        if (!StringUtil.isEmpty(map.get("loginUser")) && Constant.OK.equals(map.get("loginUser").toString())) {
            String token = request.getHeader(jwtTokenConfig.getHeader());
            Claims claims = jwtTokenConfig.getClaimByToken(token);
            String userId = (String)claims.get(jwtTokenConfig.getSub());
            map.put("loginUser", userId);
        }
        List<Map<String, Object>> list = priviLineCustomMapper.getLine(map);
        //判断是否为空
        if (list != null && list.size() > 0 && (!StringUtil.isEmpty(map.get("lineId")) || !StringUtil.isEmpty(map.get("lineName")))) {
            Set<String> list1 = new HashSet<>();
            for (int i = 0; i < list.size(); i++) {
                if (!StringUtil.isEmpty(list.get(i).get("nodePath"))) {
                    //转换成String格式
                    String path = list.get(i).get("nodePath").toString();
                    String[] str = path.split("\\.");
                    for (int j = 0; j < str.length; j++) {
                        list1.add(str[j]);
                    }
                }
            }
            map.put("list", new ArrayList<>(list1));
            List<Map<String , Object>> listDate = priviLineCustomMapper.getLineData(map);
            return Result.ok(listDate);
        } else {
            return Result.ok(list);
        }
    }
    /**
     * 新增条线管理
     *
     * @param priviLine 请求参数
     * @return Map<String, Object> 操作返回结果
     */
    @Transactional
    public Result insert(PriviLine priviLine, HttpServletRequest request) {
        PriviLine priviLine1 = priviLineMapper.selectByPrimaryKey(priviLine.getLineId());
        if (priviLine1 != null && !StringUtil.isEmpty(priviLine1.getLineId())) {
            return Result.error("-1", "该条线已存在");
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("lineId", priviLine.getUpperId());
            map.put("corpId", priviLine.getCorpId());
            //String seqId = sequenceGeneratorService.getNextIdStr("LINE", "LINE");
            List<Map<String, Object>> list = priviLineCustomMapper.selPath(map);
            if (list != null && list.size() > 0) {
                priviLine.setNodePath(list.get(0).get("nodePath").toString() + priviLine.getLineId() + ".");
                if (StringUtil.isEmpty(priviLine.getLevelId())) {//判断层级标识是否为空
                    priviLine.setLevelId(new BigDecimal(Integer.parseInt(list.get(0).get("levelId").toString()) + 1));
                }
            } else {
                priviLine.setNodePath("." + priviLine.getLineId() + ".");
                priviLine.setLevelId(new BigDecimal(1));
            }
            String token = request.getHeader(jwtTokenConfig.getHeader());
            Claims claims = jwtTokenConfig.getClaimByToken(token);
            String userId = (String)claims.get(jwtTokenConfig.getSub());
            int seq = priviLineCustomMapper.getMaxSeqId();
            priviLine.setSerialNo(new BigDecimal(seq));
            priviLine.setCreateUser(userId);
            priviLine.setCreateTime(DateTimeUtil.getStrFromNewDate());
            priviLine.setUpdateUser(userId);
            priviLine.setUpdateTime(DateTimeUtil.getStrFromNewDate());
            priviLineMapper.insertSelective(priviLine);
            return Result.OK_EMPTY;
        }
    }

    /**
     * 修改条线管理
     *
     * @param priviLine 请求参数
     * @return Map<String, Object> 操作返回结果
     */
    @Transactional
    public void update(PriviLine priviLine, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("lineId", priviLine.getUpperId());
        map.put("corpId", priviLine.getCorpId());
        if (!StringUtil.isEmpty(priviLine.getNodePath()) && Constant.EXIST.equals(priviLine.getNodePath())) {
            List<Map<String, Object>> list = priviLineCustomMapper.selPath(map);
            if (list != null && list.size() > 0) {
                priviLine.setNodePath(list.get(0).get("nodePath").toString() + priviLine.getLineId() + ".");
            } else {
                priviLine.setNodePath("." + priviLine.getLineId() + ".");
            }
        } else {
            priviLine.setNodePath(null);
        }
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        priviLine.setUpdateUser(userId);
        priviLine.setUpdateTime(DateTimeUtil.getStrFromNewDate());
        priviLineMapper.updateByPrimaryKeySelective(priviLine);
    }


    /**
     * 删除条线管理
     *
     * @param map 请求参数
     * @return Map<String, Object> 操作返回结果
     */
    @Transactional
    public void delete(List<String> map) {
        // 删除参数
        for (String appId : map) {
            priviLineCustomMapper.updateLine(appId);
            priviLineMapper.deleteByPrimaryKey(appId);
        }
    }
}
